package com.yzt.minemodule.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.yzt.zhuju.arouter.RouterMine;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.utils.VideoPlayerManager;
import com.yzt.minemodule.R;
import com.yzt.p_base.utils.ToastUtil;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.DecimalFormat;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * author : bob
 * date   : 2023/2/22
 * desc   :
 */
@Route(path = RouterMine.ACTIVITY_VIDEO_PLAY)
public class VideoPlayActivity extends BaseActivity implements SurfaceHolder.Callback, SeekBar.OnSeekBarChangeListener {

    @Autowired
    String status;

    @Autowired
    String mFileUrlPath;

    @Autowired
    String mFilePath;

//    private String mFilePath;
    //  private String mFileUrlPath = "http://gslb.miaopai.com/stream/3D~8BM-7CZqjZscVBEYr5g__.mp4";
    /**
     * 1为本地视频  2  为网络
     */
    private VideoView videoView;
    private ImageView mExitBtn;
    private Activity mActivity;
    private ImageView playVideo;
    private VideoPlayerManager playerManager;
    private boolean isPausing = true;

    /**
     * 进度条
     */
    private SeekBar seekBar;
    private boolean isPlayerPrepared = false;
    private TextView totalTime;
    private TextView currentTime;

    /**
     * 横竖屏切换
     */
    private ImageView changeLayout;
    private static final int UPDATE_PROGRESS = 4;
    private static final int FINISH = 5;
    private int vWidth, vHeight;
    private int screenWidth, screenHeight;
    private Display currDisplay;
    /**
     * 当前拖动的进度条
     */
    private int progress;

    @Override
    public int getLayoutId() {
        return R.layout.activity_video_play;
    }

    @Override
    public void installViews() {
        setFullScreen(true);

        if ("1".equals(status)) {
            //本地视频
//            if (null != getIntent()) {
//                mFilePath = getIntent().getStringExtra("path");
//            }
        } else if ("2".equals(status)) {
            //网络地址
//            if (null != getIntent()) {
//                mFileUrlPath = getIntent().getStringExtra("url");
//            }
        } else {
            ToastUtil.showMessage("Video is corrupted");
            finish();
        }

        currDisplay = this.getWindowManager().getDefaultDisplay();
        mActivity = this;
        videoView = findViewById(R.id.videoView);
        mExitBtn = findViewById(R.id.video_play_exitBtn);
        playVideo = findViewById(R.id.play_iv);
        seekBar = findViewById(R.id.progress_bar);
        totalTime = findViewById(R.id.end_tv);
        currentTime = findViewById(R.id.start_tv);
        changeLayout = findViewById(R.id.change_layout);
        videoView.getHolder().addCallback(this);
        seekBar.setOnSeekBarChangeListener(this);
        initListener();
        initPlayer();
        showMProgress();
    }

    private void initPlayer() {
        if ("1".equals(status)) {
            if (null != mFilePath && new File(mFilePath).exists()) {
                Schedulers.io().createWorker().schedule(() -> {
                    if (playerManager != null) {
                        playerManager.setupPlayback(mFilePath);
                    }
                });
            } else {
                ToastUtil.showMessage("Video is corrupted!");
            }
        } else if ("2".equals(status)) {
            Schedulers.io().createWorker().schedule(() -> {
                if (null != mFileUrlPath) {
                    if (playerManager != null) {
                        playerManager.setupPlayback(mFileUrlPath);
                    }
                }
            });
        }
    }

    private void initListener() {

        mExitBtn.setOnClickListener(view -> {
            if (!isPausing) {
                playVideo.performClick();
            }
            releasePlayerManager();
            finish();
        });

        playVideo.setOnClickListener(v -> {
            if (isPausing) {
                videoView.setVisibility(View.VISIBLE);
                if (playerManager != null) {
                    playerManager.startPlaying();
                }
                isPausing = false;
                isPlayerPrepared = true;
                playVideo.setImageResource(R.mipmap.community_video_play);
                mHandler.sendEmptyMessage(UPDATE_PROGRESS);
            } else {
                isPausing = true;
                if (playerManager != null) {
                    playerManager.pausePlaying();
                }
                playVideo.setImageResource(R.mipmap.community_video_off);
            }
        });

        changeLayout.setOnClickListener(v -> {
                    if (mActivity.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    } else {
                        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }
                }
        );

        playerManager = new VideoPlayerManager();
        playerManager.setPlayVideo(new VideoPlayerManager.IPlayVideo() {
                                       @Override
                                       public void prepare() {
                                           AndroidSchedulers.mainThread().createWorker().schedule(() -> {
                                               closeProgress();
                                               //然后开始播放视频
                                               isPlayerPrepared = true;
                                               initPortrait();
                                               seekBar.setMax(playerManager.getDuration());
                                               playVideo.performClick();
                                           });
                                       }

                                       @Override
                                       public void finish() {
                                           AndroidSchedulers.mainThread().createWorker().schedule(() ->
                                                   seekBar.setProgress(playerManager.getDuration())
                                           );
                                       }
                                   }
        );
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mExitBtn.performClick();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void releasePlayerManager() {
        if (playerManager != null) {
            playerManager.stopPlaying();
            playerManager.releasePlayer();
            playerManager = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!isPausing) {
            playVideo.performClick();
        }

        if (isFinishing()) {
            if (isPausing) {
                if (playerManager != null) {
                    playerManager.releasePlayer();
                }
            } else {
                releasePlayerManager();
            }
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (playerManager != null) {
            playerManager.setDisplay(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (playerManager != null) {
            playerManager.setDisplay(null);
        }
    }

    /**
     * 数值改变
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            this.progress = progress;
        }
    }

    /**
     * 开始拖动
     */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    /**
     * 停止拖动
     */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        try {
            if (null != playerManager && playerManager.getMediaPlyer() != null && playerManager.isPlaying()) {
                playerManager.getMediaPlyer().seekTo(progress);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATE_PROGRESS) {
                if (playerManager == null) {
                    return;
                }
                if (isPlayerPrepared && playerManager.isPlaying()) {
                    totalTime.setText(format(playerManager.getDuration()));
                    currentTime.setText(format(playerManager.getCurrentPosition()));
                    seekBar.setProgress(playerManager.getCurrentPosition());
                    this.sendEmptyMessageDelayed(UPDATE_PROGRESS, 1000);
                }
            } else if (msg.what == FINISH) {
                finish();
            }
        }
    };

    /**
     * 时间格式
     */
    private String format(int voiceLength) {
        voiceLength = voiceLength / 1000;
        DecimalFormat format = new DecimalFormat("00");
        int hour = voiceLength / 60 / 60;
        int min = voiceLength / 60 % 60;
        int sec = voiceLength % 60;
        return format.format(hour) + ":" + format.format(min) + ":" + format.format(sec);
    }

    @Override
    public void onConfigurationChanged(@NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (newConfig.orientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            //首先取得video的宽和高
            initLanScape();
        } else {
            //首先取得video的宽和高
            initPortrait();
        }
    }

    private void initPortrait() {
        if (null == playerManager || !isPlayerPrepared) {
            return;
        }
        vWidth = playerManager.getMediaPlyer().getVideoWidth();
        vHeight = playerManager.getMediaPlyer().getVideoHeight();
        screenWidth = getScreenWidth();
        screenHeight = getScreenHeight();

        if (vWidth > screenWidth && vHeight > screenHeight) {
            float wRatio = (float) vWidth / (float) screenWidth;
            float hRatio = (float) vHeight / (float) screenHeight;
            int math1 = Math.abs(vWidth - screenWidth);
            if (math1 <= 20) {
                vWidth = screenWidth = Math.max(vWidth, screenWidth);
            }
            int math2 = Math.abs(vHeight - screenHeight);
            if (math2 <= 20) {
                vHeight = screenHeight = Math.max(vHeight, screenHeight);
            }
            //选择大的一个进行缩放
            float ratio = Math.max(wRatio, hRatio);
            vWidth = (int) Math.ceil((float) vWidth / ratio);
            vHeight = (int) Math.ceil((float) vHeight / ratio);
        } else if (vHeight > screenHeight) {
            float ratio = (float) screenHeight / (float) vHeight;
            vHeight = screenHeight;
            vWidth = (int) Math.ceil((float) vWidth * ratio);
        } else {
            float ratio = (float) screenWidth / (float) vWidth;
            vWidth = screenWidth;
            vHeight = (int) Math.ceil((float) vHeight * ratio);
        }

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(vWidth, vHeight);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        videoView.setLayoutParams(layoutParams);
    }

    private void initLanScape() {
        if (null == playerManager || !isPlayerPrepared) {
            return;
        }
        vWidth = playerManager.getMediaPlyer().getVideoWidth();
        vHeight = playerManager.getMediaPlyer().getVideoHeight();
        screenWidth = currDisplay.getWidth();
        screenHeight = currDisplay.getHeight();
        if (vWidth > screenWidth && vHeight > screenHeight) {
            float wRatio = (float) vWidth / (float) screenWidth;
            float hRatio = (float) vHeight / (float) screenHeight;
            int math1 = Math.abs(vWidth - screenWidth);
            if (math1 <= 20) {
                vWidth = screenWidth = Math.max(vWidth, screenWidth);
            }
            int math2 = Math.abs(vHeight - screenHeight);
            if (math2 <= 20) {
                vHeight = screenHeight = Math.max(vHeight, screenHeight);
            }
            //选择大的一个进行缩放
            float ratio = Math.max(wRatio, hRatio);
            vWidth = (int) Math.ceil((float) vWidth / ratio);
            vHeight = (int) Math.ceil((float) vHeight / ratio);
        } else {
            float ratio = screenHeight * 1.0f / vHeight;
            vHeight = screenHeight;
            vWidth = (int) Math.ceil((float) vWidth * ratio);
        }

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(vWidth, vHeight);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        videoView.setLayoutParams(layoutParams);
    }

    /**
     * @param status “1”：本地  "2":网络
     */
    public static void startActivity(Context context, String status, String videoPath) {
        Intent intent = new Intent(context, VideoPlayActivity.class);
        intent.putExtra("statues", status);
        if ("1".equals(status)) {
            intent.putExtra("path", videoPath);
        } else {
            intent.putExtra("url", videoPath);
        }
        context.startActivity(intent);
    }

    private int getScreenWidth() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    private int getScreenHeight() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }
}